/**
 * Created by lixinkun on 2017/4/21.
 */
'use strict';
import * as TYPES from './actionTypes';
import fetchUrl from '../constants/fetchUrl';
import fetchWithTimeout from '../utils/fetchWithTimeout';
import {getYesterdayFromDate} from '../utils/getDate';
import HomeDataDAO from '../dao/HomeDataDAO';
import Toast from 'react-native-root-toast';
import px2dp from '../utils/px2dp';

function requestData() {
    return {
        type : TYPES.FETCH_HOME_DATE_REQUEST,
    };
}
//改变homeDataState
function receiveData(json, date) {
    return {
        type: TYPES.FETCH_HOME_DATA_SUCCESS,
        dataSource: json,
        dataTime: date
    };
}

function fetchFailure() {
    return {
        type: TYPES.FETCH_HOME_DATA_FAILURE
    };
}

function isValidData(responseData) {
    if (responseData.category.length > 0) {
        return true;
    } else {
        return false;
    }
}

//导出给外部使用的方法
export function onlyFetchLocalData(date) {
    return (dispatch) => {
        var dao = new HomeDataDAO();
        dao.fetchLocalData(date).then((localData) => {
            dispatch(receiveData(localData, date));
        }, (localData) => {
            //读取缓存
            dispatch(onlyFetchLocalData(getYesterdayFromDate(date)));
        })
    }
}

//导出给外部使用的方法
export function fetchDataIfNeed(date) {
    const url = fetchUrl.daily + date;
    return (dispatch => {
        dispatch(requestData());
        var dao = new HomeDataDAO();
        dao.fetchLocalData(date).then((localData) => {
            Toast.show('已是最新数据了', {position: px2dp((-80))});
            dispatch(receiveData(localData, date));
        }, (localData) => {
            fetchWithTimeout(5000, fetch(url))
                .then(response => response.json())
                .then(json => {
                    if (isValidData(json)) {
                        Toast.show('欢迎阅读最新干货', {position: px2dp(-80)});
                        dao.save(json, date);
                        dispatch(receiveData(json, date));
                    } else {
                        if (localData === null){
                            Toast.show('今日未更新，为您取往日干货', {position: px2dp(-80)});
                            dispatch(fetchDataIfNeed(getYesterdayFromDate(date)));
                        } else {
                            Toast.show('今日干货未更新', {position: px2dp(-80)});
                            dispatch(receiveData(localData, date));
                        }
                    }
                }).catch((error) => {
                console.log('获取数据出错了');
                console.log(error);
                    Toast.show('获取数据失败', {position: px2dp(-80)});
                    dispatch(fetchFailure());
                });
        });
    })
}

